<?php
		/* 
		Plugin Name: PayPal PRO Gateway
		Plugin URI: http://www.zetaprints.com/
		Version: v1.00
		Author: <a href="http://www.zetaprints.com/">ZetaPrint</a>
		Description: The PayPal PRO Gateway WordPress plugin allows you to turn a page into a credit card processing system. Just add [PAYPALPROGW] to your pages to run it! You need to send the following fields from a HTTP POST request: "item_name" (Item Name), "amount" (order total), "currency_code" (e.g USD) and "return" (the page the user is redirected to upon successful payment)
		*/
		
		// Error Message Output
		$error = urldecode(base64_decode($_REQUEST['error']));
		$ref = '';
		
		// Error Output handling
		if( $_GET['error'] )
		{
			foreach( $_GET as $key => $value ) 
			{
				$key = base64_decode($key);
				$value = base64_decode($value);
				$_REQUEST["$key"] = $value;
			}
		}
		
		// If PayPalPROGateway class does not exist, create it!
		if (!class_exists("PayPalPROGateway")) 
		{
    				class PayPalPROGateway 
				{
				
						var $adminOptionsName = "PayPalPROGatewayAdminOptions";
				
        					function PayPalPROGateway() 
						{ 
            
        					}
						
						// Display Transaction ID returned by PayPal server upon successful payment
						function show_successful_payment($content = '')
						{
								$msg = "<h4 align='center' style='font-family: Tahoma;font-size: 1.5em;font-style: normal;font-weight: bold;color: #92AC63;'>Your Payment was successfully processed!</h1>";
								$msg .= "<h4 align='center' style='font-family: Tahoma;font-size: 1.5em;font-style: normal;font-weight: bold;color: #92AC63;'>Your Transaction ID is: ";
								$msg .= "<span style='color:#0000FF'>" . base64_decode($_GET['transID']) . "</span></h4>";
								$msg .= '<p align="center" style="font-family: Verdana, Arial, Helvetica, sans-serif"><a href="' . $_GET['return'] . '"><strong>Continue</strong></a></p>';

								$find = array("[PAYPALPROGW]");
								$replace_by = array($msg);
								$content = str_replace( $find, $replace_by, $content );
            							return $content;
						}
						
						// Display Invalid Parameters notification when important fields are not posted
						function throw_invalid($content = '')
						{
								$find = array("[PAYPALPROGW]");
								$replace_by = array("<h1 style='font-family: Tahoma;font-size: 1.5em;font-style: normal;font-weight: bold;color: #92AC63;'>Missing Payment Parameters.<br>Please go back and try again!</h1>");
								$content = str_replace( $find, $replace_by, $content );
            								return $content;
						}
						
						// Add Javascript and CSS files inclusion in HTML HEAD section
						function add_headers() 
						{
            								echo '<link type="text/css" rel="stylesheet" href="' . get_bloginfo('wpurl') . '/wp-content/plugins/PayPalPROGateway/css/styles.css" />' . "\n";
            								echo '<script src="' . get_bloginfo('wpurl') . '/wp-content/plugins/PayPalPROGateway/js/form_checks.js" language="javascript"></script>' . "\n";
						}			
							
						// Display Payment Form	
						function add_payment_form($content = '') 
						{
								global $error;
																
								$payment_form = file_get_contents( $_SERVER['DOCUMENT_ROOT'] . "" . dirname($_SERVER['PHP_SELF']) . "/wp-content/plugins/PayPalPROGateway/templates/payment_form.htm" );
								
								$find = array("[PAYPALPROGW]","{REQUEST_URI}","{amount}","{item_name}","{currency_code}","{return}", "{BillingFirstName}", "{BillingFirstName}", "{BillingLastName}", "{BillingStreet1}", "{BillingStreet2}", "{BillingCityName}", "{BillingPostalCode}", "{BillingPhone}", "{img_path}", "{error}");
								$replace_by = array($payment_form, $_SERVER['REQUEST_URI'], $_REQUEST['amount'], $_REQUEST['item_name'], $_REQUEST['currency_code'], $_REQUEST['return'], $_REQUEST['BillingFirstName'], $_REQUEST['BillingFirstName'], $_REQUEST['BillingLastName'], $_REQUEST['BillingStreet1'], $_REQUEST['BillingStreet2'], $_REQUEST['BillingCityName'], $_REQUEST['BillingPostalCode'], $_REQUEST['BillingPhone'], get_bloginfo('wpurl') . '/wp-content/plugins/PayPalPROGateway/images/', $error);
								
								$content = str_replace( $find, $replace_by, $content );
            							return $content;
        					} 

  						// Retrieve Backend current options values
              					function getAdminOptions()
						{
                  						$PayPalPROGWAdminOptions = array(  

								'environment' => 'sandbox',
                     						'api_username' => 'holy.w_1218172414_biz_api1.gmail.com',
                      						'api_password' => '1218172419',
								'api_signature' => 'AiPC9BjkCyDFQXbSkoZcgqH3hpacA5wiZJsFy5to140BAh1KdW1IB6zX',
								'proxy_server' => 'http://proxy.shr.secureserver.net',
                      						'proxy_port' => '3128');

                 							$devOptions = get_option($this->adminOptionsName);
                  							if (!empty($devOptions)) 
									{
                      								foreach ($devOptions as $key => $option) $PayPalPROGWAdminOptions[$key] = $option; 
                  							}            

                  							update_option($this->adminOptionsName, $PayPalPROGWAdminOptions);
                  							return $PayPalPROGWAdminOptions;
              						}
							
							// Retrieve Options
     						 	function init()
						 	{
                  							$this->getAdminOptions();
              						}

							// Admin Setting for the plugin
							function printAdminPage() 
							{
									$pppgwOptions = $this->getAdminOptions();

									if (isset($_POST['update_PayPalPROGatewaySettings'])) 
									{
										if (isset($_POST['environment'])) 
										{
                            								$pppgwOptions['environment'] = $_POST['environment'];
                        							}

										if (isset($_POST['api_username'])) 
										{
                            								$pppgwOptions['api_username'] = $_POST['api_username'];
                        							}

										if (isset($_POST['api_password'])) 
										{
                            								$pppgwOptions['api_password'] = $_POST['api_password'];
                        							}

										if (isset($_POST['api_signature'])) 
										{
                            								$pppgwOptions['api_signature'] = $_POST['api_signature'];
                        							}

										if (isset($_POST['proxy_server'])) 
										{
                            								$pppgwOptions['proxy_server'] = $_POST['proxy_server'];
                        							}

										if (isset($_POST['proxy_port'])) 
										{
                            								$pppgwOptions['proxy_port'] = $_POST['proxy_port'];
                        							}
										update_option($this->adminOptionsName, $pppgwOptions);
										?>
										<div class="updated"><p><strong><?php _e("Settings Updated.", "PayPalPROGateway");?></strong></p></div>
										<?php
										
									}

								?>

<div class=wrap>
<form method="post" action="<?php echo $_SERVER["REQUEST_URI"]; ?>">
<h2>PayPal PRO Payment Gateway for WordPress</h2>
<h3>Environment</h3>
<p>Define the plugin environment. Possible values are "live", "sandbox" and "beta-sandbox".</p>
<p><label for="environment">
<select name="environment">



	<option value="live"<?php if ($pppgwOptions['environment'] == "live") { _e(' selected', "PayPalPROGateway"); }?>/>Live</option>
	<option value="sandbox"<?php if ($pppgwOptions['environment'] == "sandbox") { _e(' selected', "PayPalPROGateway"); }?>/>Sandbox</option>
	<option value="beta-sandbox"<?php if ($pppgwOptions['environment'] == "beta-sandbox") { _e(' selected', "PayPalPROGateway"); }?>/>Beta Sandbox</option>
</select>
</p>

<h3>API Username</h3>
<p>PayPal PRO API Username.</p>
<p><label for="api_username"><input type="text" id="api_username" name="api_username" value="<?php _e($pppgwOptions['api_username'], 'PayPalPROGateway') ?>" size="50" /></p>
 
<h3>API Password</h3>
<p>PayPal PRO API Password.</p>
<p><label for="api_password"><input type="text" id="api_password" name="api_password" value="<?php _e($pppgwOptions['api_password'], 'PayPalPROGateway') ?>"  /></p>
 
<h3>API Signature</h3>
<p>PayPal PRO API Signature.</p>
<p><label for="api_signature"><input type="text" id="api_signature" name="api_signature" value="<?php _e($pppgwOptions['api_signature'], 'PayPalPROGateway') ?>" size="50" /></p>
 
<h3>Proxy Server</h3>
<p>Proxy Server domain name or IP address for SSL in cURL.</p>
<p><label for="proxy_server"><input type="text" id="proxy_server" name="proxy_server" value="<?php _e($pppgwOptions['proxy_server'], 'PayPalPROGateway') ?>" size="50" /></p>
 
<h3>Proxy Server port</h3>
<p>Proxy server port for SSL in cURL</p>
<p><label for="proxy_port"><input type="text" id="proxy_port" name="proxy_port" value="<?php _e($pppgwOptions['proxy_port'], 'PayPalPROGateway') ?>"  /></p>
 
<div class="submit">
<input type="submit" name="update_PayPalPROGatewaySettings" value="<?php _e('Update Settings', 'PayPalPROGateway') ?>" /></div>
</form>
 </div>


								<?php

							}


    				}
		} 
		
		// If PayPalPROGateway class exists create an instance!
		if (class_exists("PayPalPROGateway")) 
		{
    			$dl_paypalGateway = new PayPalPROGateway();
		}	

		//Initialize the admin panel
		if (!function_exists("PayPalPROGateway_ap")) 
		{
    			function PayPalPROGateway_ap() 
			{
        			global $dl_paypalGateway;
        			if (!isset($dl_paypalGateway)) 
				{
            				return;
        			}
        			if (function_exists('add_options_page')) 
				{
    					add_options_page('PayPal PRO Payment Gateway', 'PayPal PRO Payment Gateway', 9, basename(__FILE__), array(&$dl_paypalGateway, 'printAdminPage'));
        			}
    			}   
		} 

		//Actions and Filters   
		if (isset($dl_paypalGateway)) 
		{		
				add_action('activate_PayPalPROGateway/PayPalPROGateway.php',  array(&$dl_paypalGateway, 'init'));
				add_action('admin_menu', 'PayPalPROGateway_ap'); 

				if( !empty($_GET['transID']) )
				{
						add_filter('the_content', array(&$dl_paypalGateway, 'show_successful_payment'));
				}
				elseif( empty($_REQUEST['item_name']) or empty($_REQUEST['amount']) or empty($_REQUEST['return']) )
				{
						add_filter('the_content', array(&$dl_paypalGateway, 'throw_invalid'));
				}
				else
				{
						if( !empty($_REQUEST['Pay']) )
						{
								$PPPGWOptions = $dl_paypalGateway->getAdminOptions();
								$error = process_payment( $PPPGWOptions['environment'], $PPPGWOptions['api_username'], $PPPGWOptions['api_password'], $PPPGWOptions['api_signature'], $PPPGWOptions['proxy_server'], $PPPGWOptions['proxy_port'] );
								
								$tb = explode("|", $error);					
								if($tb[0] == 'error')
								{
										add_action('wp_head', array(&$dl_paypalGateway, 'add_headers'), 1);
										add_filter('the_content', array(&$dl_paypalGateway, 'add_payment_form'));
										foreach( $_REQUEST as $key => $value ) if( $key != 'Pay' ) $data[] = base64_encode($key) . "=" . base64_encode($value);
										$data = implode("&", $data);
										if( strstr($_SERVER['REQUEST_URI'], '?') )
										{
												header("Location: " . $_SERVER['REQUEST_URI'] . '&error=' . base64_encode($tb[1]) . '&' . $data );
										}
										else
										{
												header("Location: " . $_SERVER['REQUEST_URI'] . '?error=' . base64_encode($tb[1]) . '&' . $data );
										}
										exit();
								}	
								else
								{
										if( strstr($_SERVER['REQUEST_URI'], '?') )
										{
												header("Location: " . $_SERVER['REQUEST_URI'] . '&transID=' . base64_encode($tb[1]) . '&return=' . $_REQUEST['return'] );
										}
										else
										{
												header("Location: " . $_SERVER['REQUEST_URI'] . '?transID=' . base64_encode($tb[1]) . '&return=' . $_REQUEST['return'] );
										}
										exit();
								}
						}
						else
						{
								add_action('wp_head', array(&$dl_paypalGateway, 'add_headers'), 1);
								add_filter('the_content', array(&$dl_paypalGateway, 'add_payment_form'));
						}
				}
		
		}
		
/** PayPal API - DoDirectPayment NVP;
 *
 *  Process a credit card payment. 
*/

/**
 * Send HTTP POST Request
 *
 * @param	string	The API method name
 * @param	string	The POST Message fields in &name=value pair format
 * @return	array	Parsed HTTP Response body
 */
function PPHttpPost($methodName_, $nvpStr_, $environment, $api_username, $api_password, $api_signature, $proxy_server = '', $proxy_port = '') {
						
	// Set up your API credentials, PayPal end point, and API version.
	$API_UserName = urlencode($api_username);
	$API_Password = urlencode($api_password);
	$API_Signature = urlencode($api_signature);
	$API_Endpoint = "https://api-3t.paypal.com/nvp";
	if("sandbox" === $environment || "beta-sandbox" === $environment) {
		$API_Endpoint = "https://api-3t.$environment.paypal.com/nvp";
	}
	$version = urlencode('51.0');

	// Set the curl parameters.
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $API_Endpoint);
	curl_setopt($ch, CURLOPT_VERBOSE, 1);

	// Turn off the server and peer verification (TrustManager Concept).
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
	if( $proxy_server and $proxy_port )
	{
			curl_setopt ($ch, CURLOPT_HTTPPROXYTUNNEL, TRUE);
			curl_setopt ($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
			curl_setopt ($ch, CURLOPT_PROXY, "$proxy_server:$proxy_port");
			curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
	}
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_POST, 1);

	// Set the API operation, version, and API signature in the request.
	$nvpreq = "METHOD=$methodName_&VERSION=$version&PWD=$API_Password&USER=$API_UserName&SIGNATURE=$API_Signature$nvpStr_";

	// Set the request as a POST FIELD for curl.
	curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);

	// Get response from the server.
	$httpResponse = curl_exec($ch);

	if(!$httpResponse) {
		exit("$methodName_ failed: ".curl_error($ch).'('.curl_errno($ch).')');
	}

	// Extract the response details.
	$httpResponseAr = explode("&", $httpResponse);

	$httpParsedResponseAr = array();
	foreach ($httpResponseAr as $i => $value) {
		$tmpAr = explode("=", $value);
		if(sizeof($tmpAr) > 1) {
			$httpParsedResponseAr[$tmpAr[0]] = $tmpAr[1];
		}
	}

	if((0 == sizeof($httpParsedResponseAr)) || !array_key_exists('ACK', $httpParsedResponseAr)) {
		exit("Invalid HTTP Response for POST request($nvpreq) to $API_Endpoint.");
	}
	
	return $httpParsedResponseAr;
}


		function process_payment( $environment, $api_username, $api_password, $api_signature, $proxy_server = '', $proxy_port = '' )
		{				
				// Set request-specific fields.
				$paymentType = urlencode('Authorization');				// or 'Sale'
				$firstName = urlencode($_POST['BillingFirstName']);
				$lastName = urlencode($_POST['BillingLastName']);
				$creditCardType = urlencode($_POST['CreditCardType']);
				$creditCardNumber = urlencode($_POST['CreditCardNumber']);
				$expDateMonth = $_POST['ExpMonth'];
				// Month must be padded with leading zero
				$padDateMonth = urlencode(str_pad($expDateMonth, 2, '0', STR_PAD_LEFT));
				$expDateYear = urlencode($_POST['ExpYear']);
				$cvv2Number = urlencode($_POST['CVV2']);
				$address1 = urlencode($_POST['BillingStreet1']);
				$address2 = urlencode($_POST['BillingStreet2']);
				$city = urlencode($_POST['BillingCityName']);
				$state = urlencode($_POST['BillingStateOrProvince']);
				$zip = urlencode($_POST['BillingPostalCode']);
				$country = urlencode($_POST['BillingCountry']);				// US or other valid country code
				$amount = urlencode($_POST['amount']);
				$currencyID = urlencode($_POST['currency_code']);							// USD or other currency ('GBP', 'EUR', 'JPY', 'CAD', 'AUD')

				// Add request-specific fields to the request string.
				$nvpStr =	"&PAYMENTACTION=$paymentType&AMT=$amount&CREDITCARDTYPE=$creditCardType&ACCT=$creditCardNumber".
							"&EXPDATE=$padDateMonth$expDateYear&CVV2=$cvv2Number&FIRSTNAME=$firstName&LASTNAME=$lastName".
							"&STREET=$address1&CITY=$city&STATE=$state&ZIP=$zip&COUNTRYCODE=$country&CURRENCYCODE=$currencyID";
				
				// Execute the API operation; see the PPHttpPost function above.
				$httpParsedResponseAr = PPHttpPost('DoDirectPayment', $nvpStr, $environment, $api_username, $api_password, $api_signature, $proxy_server, $proxy_port);
				
				if("Success" == $httpParsedResponseAr["ACK"]) 
				{
						return "success|{$httpParsedResponseAr['TRANSACTIONID']}";
						//header("Location: payment_success.php?transID={$httpParsedResponseAr['TRANSACTIONID']}&return={$_POST['return']}");
						//exit('Direct Payment Completed Successfully: '.print_r($httpParsedResponseAr, true));
				} 
				else  
				{
						return "error|{$httpParsedResponseAr["L_LONGMESSAGE0"]}"; 
						//$error = urldecode($httpParsedResponseAr["L_LONGMESSAGE0"]);
						//exit('DoDirectPayment failed: ' . print_r($httpParsedResponseAr, true));
				}
		}

		
		

?>